package com.joysuch.wwyt.bp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joysuch.wwyt.bp.bean.investigate.BpInvestigateRecordHisQueryBean;
import com.joysuch.wwyt.bp.bean.investigate.vo.BpInvestigateRecordHisVO;
import com.joysuch.wwyt.bp.entity.BpInvestigateRecordHis;
import com.joysuch.wwyt.bp.mapper.BpInvestigateRecordHisMapper;
import com.joysuch.wwyt.bp.service.BpInvestigateRecordHisService;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 描述：检查记录-历史
 *
 * @author zhangcancan
 * @date 2023/6/8 14:05
 **/
@Service
public class BpInvestigateRecordHisServiceImpl extends ServiceImpl<BpInvestigateRecordHisMapper, BpInvestigateRecordHis> implements BpInvestigateRecordHisService {

    @Autowired
    private BaseUserDao baseUserDao;

    @Override
    public Page<BpInvestigateRecordHisVO> pageByCheckPlanId(BpInvestigateRecordHisQueryBean queryBean) {

        Page<BpInvestigateRecordHis> page = new Page<>(queryBean.getPage() + 1, queryBean.getSize());

        Page<BpInvestigateRecordHisVO> bpInvestigateRecordHisVOPage = this.baseMapper.pageBpInvestigateRecordHis(page, queryBean);
        convertUser(bpInvestigateRecordHisVOPage.getRecords());

        return bpInvestigateRecordHisVOPage;
    }

    /**
     * 转义用户
     */
    private void convertUser(List<BpInvestigateRecordHisVO> records) {

        if (CollectionUtil.isEmpty(records)) {
            return ;
        }

        // 用户ids
        List<Long> userIds = records.stream().map(BpInvestigateRecordHisVO::getCheckUserId).distinct().collect(Collectors.toList());

        Map<Long, String> userNameMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(userIds)) {
            userNameMap = baseUserDao.getAllByIds(userIds)
                    .stream().collect(Collectors.toMap(BaseUser::getId, BaseUser::getRealName));
        }

        for (BpInvestigateRecordHisVO record : records) {
            record.setCheckUserName(userNameMap.get(record.getCheckUserId()));
        }
    }

}
